Jump Statements are used to skip execution of subsequent code
● break completely exits current or labelled Loop Statement
● continue skips execution of remaining current iteration of current or labelled Loop (continues with next iteration)
● return returns from the function by skipping execution of the remaining function code
break statement is used to completely exit Loop Statements and Switch Blocks.
This means that remaining of the current iteration and all subsequent iterations of the Loop Statement are skipped.
Exit loop
//EXIT NEAREST LOOP.
for(i in 1..5) {
if(i==3) { break } //Exit nearest Loop.
print(i) //1, 2
}
//EXIT LABELED LOOP.
myloop@
for(i in 1..5) {
for(j in 10..15) {
if(j==13) { break@myloop } //Exit labeled Loop.
println(j) //10, 11, 12
}
}
continue statement is used to skip only the remaining of the current iteration of the Loop Statement.
But subsequent iterations of the Loop Statement are to be executed normally.
Continue with next iteration
//CONTINUE WITH NEAREST LOOP.
for(i in 1..5) {
if(i==3) { continue } //Continue with nearest Loop.
print(i) //1, 2, 4, 5
}
//CONTINUE WITH LABELED LOOP.
myloop@
for(i in 1..3) {
for(j in 10..15) {
if(j==13) { continue@myloop } //Continue with labeled Loop.
println(j) //(10, 11, 12) (10, 11, 12) (10, 11, 12)
}
}